// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ReportBuilderCmdletGroup.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Extensions.ReportBuilder
{
    #region Using Directives

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;

    using Org.OpenTrader.Extensions.ReportBuilder.UI.Forms;
    using Org.OpenTrader.Framework;
    using Org.OpenTrader.Framework.Cmdlet;
    using Org.OpenTrader.Framework.DataModel;
    using Org.OpenTrader.Framework.Forge.DataModel;

    #endregion

    /// <summary>
    /// The execution context command group.
    /// </summary>
    public class ReportBuilderCmdletGroup : CmdletGroup
    {
        #region Constants and Fields

        /// <summary>
        /// The commands.
        /// </summary>
        private readonly IDictionary<string, Cmdlet> commands;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ReportBuilderCmdletGroup"/> class.
        /// </summary>
        public ReportBuilderCmdletGroup()
        {
            this.commands = new Dictionary<string, Cmdlet>();

            Cmdlet cmd;

            cmd = new BuildCmdlet(this);
            this.commands[cmd.Name] = cmd;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets Cmdlets.
        /// </summary>
        public override IDictionary<string, Cmdlet> Cmdlets
        {
            get
            {
                return this.commands;
            }
        }

        /// <summary>
        /// Gets Help.
        /// </summary>
        public override string Help
        {
            get
            {
                return "This command group is used to create reports";
            }
        }

        /// <summary>
        /// Gets Name.
        /// </summary>
        public override string Name
        {
            get
            {
                return "report_builder";
            }
        }

        #endregion

        /// <summary>
        /// The run command.
        /// </summary>
        public class BuildCmdlet : Cmdlet
        {
            #region Constants and Fields

            /// <summary>
            /// The identity.
            /// </summary>
            private static readonly Identity Identity = Identity.Create(System.Reflection.MethodBase.GetCurrentMethod());

            #endregion

            #region Constructors and Destructors

            /// <summary>
            /// Initializes a new instance of the <see cref="BuildCmdlet"/> class.
            /// </summary>
            /// <param name="cmdletGroup">
            /// The command group.
            /// </param>
            public BuildCmdlet(CmdletGroup cmdletGroup)
                : base(cmdletGroup)
            {
            }

            #endregion

            #region Properties

            /// <summary>
            /// Gets Help.
            /// </summary>
            public override string Help
            {
                get
                {
                    return "build a report using given orderservice and booking path";
                }
            }

            /// <summary>
            /// Gets Name.
            /// </summary>
            public override string Name
            {
                get
                {
                    return "build";
                }
            }

            /// <summary>
            /// Gets Usage.
            /// </summary>
            public override string Usage
            {
                get
                {
                    return string.Format("{0} {1} orderservice_id booking_path", this.CmdletGroup.Name, this.Name);
                }
            }

            #endregion

            #region Public Methods

            /// <summary>
            /// The execute.
            /// </summary>
            /// <param name="args">
            /// The args.
            /// </param>
            /// <returns>
            /// </returns>
            public override Status Execute(string[] args)
            {
                if (args.Length < 2)
                {
                    return Status.Failure(Identity, "parameter context_id or booking_path is missing");
                }

                var bookingPath = PathUtil.Cleanup(args[1]);
                var contextId = Guid.Empty;
                try
                {
                    contextId = new Guid(args[0]);
                }
                catch (Exception)
                {
                    return Status.Failure(Identity, string.Format("The parameter context_id={0} is not valid, cannot convert to Guid", args[0]));
                }

                // TODO splt
                var nodeId = Guid.Empty; // bookingpath (string) -> find node

                // Create the orders data source
                IList<Order> orders = new List<Order>();
                var db_orders = from db_order in Singleton<DBForge>.Instance.Entities.DBOrder
                                where db_order.DBBackOffice.ID == contextId
                                where db_order.DBExecutionContextINodeID == nodeId
                                orderby db_order.TimeStamp descending
                                select db_order;

                Console.WriteLine(
                    string.Format("Building a report with orders related to OrderService {0} and inside booking path {1}", contextId, bookingPath));

                // Console.WriteLine(string.Format("Using {0}", db_orders.Expression.ToString()));
                var n = 0;
                foreach (var db_order in db_orders)
                {
                    var db_instrument = DBInstrumentStaticDataHelpers.GetDBInstrumentStaticData(db_order.DBInstrumentStaticDataID);
                    var order = new Order(db_order, db_instrument, n);
                    orders.Add(order);
                    n++;
                }

                if (n > 0)
                {
                    Console.WriteLine(string.Format("  {0} matching order(s) found. Building report.", n));
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    var control = new UIOrderReport(orders);
                    control.Run(string.Format("Report Builder {0} {1}", contextId, bookingPath));
                }
                else
                {
                    Console.WriteLine("  No matching orders were found. No report was built.");
                }

                return Status.Success(Identity);
            }

            #endregion
        }
    }
}